<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clearType="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-print>
            <!-- <el-button :disabled="!canPrint" @click="print()">打印</el-button> -->
            <PopoverPrint
              ref="popoverShow"
              v-model:popoverVisible="popoverVisible"
              :canPrint="canPrint"
              :templateArr="templateArr"
              @tempClick="tempClick"
              @print="print"
            ></PopoverPrint>
          </template>
          <template v-slot:filter-download>
            <el-button @click="exportExcel()">导出excel</el-button>
          </template>
          <template v-slot:filter-examine>
            <el-button :disabled="!canExamine" @click="examine()"
              >批准</el-button
            >
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </TableContainer>
    </div>

    <OrderModify
      v-if="modifyInfo.visible"
      :id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />

    <OrderDetail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :table-row="detailInfo.data"
      @returnBack="getList"
    />
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <PageDialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </PageDialog>
  </div>
</template>

<script setup name="originalAmountAdjust">
import {
  adjustOrderCustomizeListPage,
  deleteAdjustOrder,
  submitAdjustOrder,
  flowSubmitAdjustOrder,
  checkAdjustOrder,
  rejectAdjustOrder,
  flowRejectAdjustOrder,
  refuseAdjustOrder,
  flowRefuseAdjustOrder,
  revokeAdjustOrder,
  cancelAdjustOrder,
  cancelAuditAdjustOrder,
  adjustAdjustOrder,
  excelAdjustOrderList,
  printAdjustOrderList,
  refushOrderDetail,
} from '@/api/asset.js'
import { getBusinessKeyById } from '@/api/flowable'
import OrderModify from './modify'
import OrderDetail from './details'
import { fatchTemplateByCode } from '@/api/base'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { selectByCodeAndDept } from '@/api/report'
import { doPrint } from '@/utils/exportUtil'
const detailList = defineAsyncComponent(() => import('./detailList'))
const { proxy } = getCurrentInstance()

const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      adjustType: {
        value: 1,
        queryCategory: 'AND',
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('originalAmountAdjust:add'),
    },
    {
      // 批准
      type: 'slot',
      value: 'examine',
      show:
        proxy.$permission('originalAmountAdjust:examine') &&
        proxy.$store.state.permission.systemConfig.assets_adjust_audit_type ==
          1,
    },
    {
      // 导出
      type: 'slot',
      value: 'download',
      show: proxy.$permission('originalAmountAdjust:download'),
    },
    {
      // 打印
      type: 'slot',
      value: 'print',
      show: proxy.$permission('originalAmountAdjust:printOrder'),
    },
  ],
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      // /ratify 批准
      // /reject 驳回
      // /refuse 拒绝 -1
      // /submit 提交
      // /revoke 撤回
      // /cancelAudit 销审 -1
      // /excelList 导出excel 主单据
      // ////以下是流程相关
      // /flowSubmit 流程提交
      // /flowApproved 流程批准
      // /flowReject 流程驳回
      // /flowRefuse 流程拒绝

      // 1 待提交  2 待审核  4 完成  6 审批中  7 已拒绝 8  已驳回
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('originalAmountAdjust:submit'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 8
        },
      },
      {
        label: '批准',
        event: examine,
        show: proxy.$permission('originalAmountAdjust:examine'),
        ifRender: function (row) {
          return (
            row.status === 2 &&
            proxy.$store.state.permission.systemConfig
              .assets_adjust_audit_type == 1
          )
        },
      },
      {
        label: '驳回',
        event: reject,
        show: proxy.$permission('originalAmountAdjust:reject'),
        ifRender: function (row) {
          return (
            row.status === 2 &&
            proxy.$store.state.permission.systemConfig
              .assets_adjust_audit_type == 1
          )
        },
      },
      {
        label: '拒绝',
        event: refuse,
        show: proxy.$permission('originalAmountAdjust:refuse'),
        ifRender: function (row) {
          return (
            row.status === 2 &&
            proxy.$store.state.permission.systemConfig
              .assets_adjust_audit_type == 1
          )
        },
      },
      {
        label: '销审',
        event: cancelAudit,
        show: proxy.$permission('originalAmountAdjust:cancelAudit'),
        ifRender: function (row) {
          return (
            row.status === 4 &&
            proxy.$store.state.permission.systemConfig
              .assets_adjust_audit_type != 0
          )
        },
      },
      {
        label: '撤回',
        event: revoke,
        show: proxy.$permission('originalAmountAdjust:revoke'),
        ifRender: function (row) {
          return (
            row.status === 2 ||
            (row.status === 4 &&
              proxy.$store.state.permission.systemConfig
                .assets_adjust_audit_type == 0)
          )
        },
      },
      // {
      //   label: '取消',
      //   event: cancel,
      //   show: proxy.$permission('originalAmountAdjust:cancel'),
      //   ifRender: function (row) {
      //     return row.status === 4
      //   },
      // },

      {
        label: '修改',
        event: update,
        show: proxy.$permission('originalAmountAdjust:update'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 8
        },
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('originalAmountAdjust:del'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 8
        },
      },
    ],
  },
})
const modifyInfo = ref({
  visible: false,
  id: '',
  title: '',
})
const detailListInfo = ref({
  visible: false,
})
const detailInfo = ref({
  visible: false,
  data: {},
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const clearType = ref(true)
const slipSelectRequest = ref(true)

const canExamine = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 2).length
  )
})

const canPrint = computed(() => {
  return true
})

watch(
  () => proxy.$router.currentRoute.value.name,
  (to, from) => {
    if (!from) return
    if (
      from.includes('myPendingDetail') ||
      from.includes('myFinishedDetail') ||
      from.includes('myApplyDetail')
    ) {
      getList()
    }
  },
  {
    deep: true,
  }
)

let obj = {
  typeValue: {
    label: '类型',
    value: 'typeValue',
    asValue: 'type',
    componentType: 'select-model',
    code: 'asset_adjust_type',
    show: false,
    hidden: true,
  },
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'asset_adjust_order_status',
    show: false,
    hidden: true,
  },
}

tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})

getCustomize()

function handleClose() {
  dialogInfo.value.visible = false
}
function pageInfo(obj) {
  page.value = obj
}
function examine(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  checkAdjustOrder(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.value.type === 'print') {
    printList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function exportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = true
}
function exportExcelList() {
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogInfo.value.flag,
  }
  excelAdjustOrderList(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
const popoverVisible = ref(false)
const templateArr = ref([])
async function print() {
  selectByCodeAndDept({
    tempCode: 'adjustOriginalList',
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        console.log(proxy.$refs.popoverShow)
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {},
          callback: printCallback,
          data: {
            customParam: JSON.stringify({
              ...filterInfo.value.query,
              ...page.value,
              page: dialogInfo.value.flag === 'page' ? true : false,
            }),
          },
        })
      }
    }
  })
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      ...filterInfo.value.query,
    },
    callback: printCallback,
    data: {},
  })
  popoverVisible.value = false
}

function printCallback() {
  try {
    // 打印成功增加打印次数
    // updatePrintCount({
    //   orderNo: infoList.value.data.orderNo,
    //   orderId: props.orderId,
    //   tempCode: 'paymentDeatil',
    //   orderType: 0,
    // })
  } catch (error) {}
}
//打印
function printList() {
  fatchTemplateByCode({
    resourceCode: 'originalAmountAdjust:printOrderList',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.value.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: flag,
  }
  printAdjustOrderList(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function reject(row = undefined) {
  //驳回
  proxy
    .$prompt('请输入驳回理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: '驳回理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        id: row.id,
        orderId: row.id,
        checkOpt: value,
      }
      rejectAdjustOrder(data).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
}
function refuse(row) {
  proxy
    .$prompt('请输入拒绝理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: '拒绝理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        id: row.id,
        orderId: row.id,
        checkOpt: value,
      }
      refuseAdjustOrder(data).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
}
function cancelAudit(row) {
  cancelAuditAdjustOrder([row.id]).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function cancel(row = undefined) {
  //取消
  cancelAdjustOrder([row.id]).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function returnModify() {
  if (modifyInfo.value.id) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  // let filterInfo = filterInfo.value
  filterInfo.value.query.queryMap = {}
  let arr = [
    {
      fieldName: 'adjustType',
      queryType: 'EQUALS',
      value: 1,
      queryCategory: 'AND',
    },
  ]
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  // let filterInfo = filterInfo.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
//删除
function remove(row) {
  deleteAdjustOrder([row.id]).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//创建
function create() {
  modifyInfo.value.id = ''
  modifyInfo.value.title = '原值调整新增'
  modifyInfo.value.visible = true
}
function update(row) {
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'assetAdjustOriginal',
  }).then((res) => {
    if (res.success) {
      sessionStorage.setItem('storeRowId', row.id)
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        //修改
        modifyInfo.value.id = row.id
        modifyInfo.value.title = '原值调整修改'
        modifyInfo.value.visible = true
      }
    }
  })
}
//提交
function submit(row = undefined) {
  if (
    proxy.$store.state.permission.systemConfig.assets_adjust_audit_type == 2
  ) {
    let data = {
      flowTaskCommentDto: { approvalType: 'submit' },
      processDefinitionKey: 'assetAdjustOriginal',
      orderId: row.id,
    }
    flowSubmitAdjustOrder(data).then((resp) => {
      if (resp && resp.success) {
        if (resp.msgType === 'messageBox') {
          refushOrderDetail(row.id).then()
        }
        getList()
      }
    })
  } else {
    submitAdjustOrder([row.id]).then((resp) => {
      if (resp && resp.success) {
        if (resp.msgType === 'messageBox') {
          refushOrderDetail(row.id).then()
        }
        getList()
      }
    })
  }
}

function revoke(row = undefined) {
  //撤回
  revokeAdjustOrder([row.id]).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//展示明细
function showDetail(row) {
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'assetAdjustOriginal',
  }).then((res) => {
    if (res.success) {
      sessionStorage.setItem('storeRowId', row.id)
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        detailInfo.value.data = row
        detailInfo.value.visible = true
      }
    }
  })
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'assetAssetManageOriginalAmountAdjustList-com.slip.spd.entity.vo.asset.AssetAdjustOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      console.log(filterInfo.value.searchList)

      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList

      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = adjustOrderCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
